import { useCallback, useRef } from "react";

export type Debounce<Callback> = Callback & {
  cancel: () => void;
};

export const useDebounce = <Callback extends Function>(
  callback: Callback,
  delay: number
) => {
  const timeoutRef = useRef<number>();

  const debouncedCallback: Debounce<Callback> = useCallback(
    (...args: unknown[]) => {
      if (timeoutRef.current) {
        clearTimeout(timeoutRef.current);
      }
      timeoutRef.current = window.setTimeout(() => {
        callback(...args);
      }, delay);
    },
    [callback, delay]
  ) as unknown as Debounce<Callback>;
  debouncedCallback.cancel = () => {
    clearTimeout(timeoutRef.current);
  };
  return debouncedCallback;
};
